
double alarmTemp;
float currentTemp;

void loop()
{
  alarmTemp = getAlarmTempLevel();
  currentTemp = getTemperature();

  DEBUG_PRINT(F("-----------------------------------------------\n"));
  DEBUG_PRINT(F("T ALARMA ")); 
  DEBUG_PRINT(alarmTemp);
  DEBUG_PRINT(F(" C. TEMP "));
  DEBUG_PRINT(currentTemp);
  DEBUG_PRINT(F("\n"));
  DEBUG_PRINT(F("-----------------------------------------------\n"));

  String alarmTempTxt =   "Alarma:    " + String(alarmTemp, FLOAT_DECIMAL_PLACES);
  String currentTempTxt = "T actual:  " + String(currentTemp, FLOAT_DECIMAL_PLACES);
  lcd.displayText(alarmTempTxt, currentTempTxt);

  processTempValues();

  unsigned long elapsed = (millis() - lastSmsCheckTime)/1000;
  //NOTA: El elapsed < 0 es por si se llega a desbordar el contador de tiempo (aprox 50 días)
  if (elapsed > SMS_CHECK_PERIOD || elapsed < 0)
  {
    lcd.displayText("Comprobando SMS", "recibidos");
    
    displayCoverageIcon();
    
    //TODO: EN LUGAR DE REVISAR LOS SMS A LO BRUTO, VER QUÉ POSICIONES ESTÁN OCUPADAS CON UN AT+CMGL
    for (int i = 0; i < 16; i++ )
    {
      String commandStr = gprs.checkReceivedCommand(i);
      processReceivedCommand(commandStr, i);
    }
    lastSmsCheckTime = millis();
  }

  //Un pequeño delay para no volver loco al puerto serie
  delay(LOOP_DELAY);
}


void processTempValues()
{
  //Ahora las comparaciones para las salidas
  if (currentTemp > alarmTemp)
  {
    setTemperatureLedStatus(HIGH, HIGH, HIGH, HIGH, HIGH);    
    alarm(currentTemp, alarmTemp);
  }
  else if (currentTemp >= (alarmTemp - sensitivity) && currentTemp < alarmTemp)
    setTemperatureLedStatus(HIGH, HIGH, HIGH, HIGH, LOW);  
  else if (currentTemp >= (alarmTemp - 2 * sensitivity) && (currentTemp < alarmTemp - sensitivity))
    setTemperatureLedStatus(HIGH, HIGH, HIGH, LOW, LOW);
  else if ((currentTemp >= (alarmTemp - 3 * sensitivity)) && (currentTemp < alarmTemp - 2 * sensitivity))
    setTemperatureLedStatus(HIGH, HIGH, LOW, LOW, LOW);
  else if(currentTemp < (alarmTemp -  3 * sensitivity))
  {
    setTemperatureLedStatus(HIGH, LOW, LOW, LOW, LOW);
    //Reseteamos la alarma para que si vuelve a dispararse la temperatura se genere un nuevo aviso
    sentSmsAlarm = false;
  }
}

void processReceivedCommand(String commandStr, int smsIndex)
{
  if (commandStr.startsWith(SMS_COMMAND_ADD_NUMBER))
  {
    commandStr = commandStr.substring(strlen(SMS_COMMAND_ADD_NUMBER) + 1, commandStr.length());
    commandStr = commandStr.substring(0, commandStr.indexOf(' '));
    DEBUG_PRINT(F("COMANDO: Add number:-->"));
    DEBUG_PRINT(commandStr);
    DEBUG_PRINT(F("<--\n"));

    Setup mySetup;
    boolean bRes = mySetup.addNumber(commandStr.c_str());
    if (bRes)
    {
      sendAddReplySms(commandStr.c_str());
      lcd.displayText("Nuevo numero", commandStr);
      delay(5000); //para que dé tiempo a leer el mensaje
      displayPhoneNumberList(mySetup);
    }
  }
  else if (commandStr.startsWith(SMS_COMMAND_DELETE_NUMBER))
  {
    commandStr = commandStr.substring(strlen(SMS_COMMAND_DELETE_NUMBER) + 1, commandStr.length());
    commandStr = commandStr.substring(0, commandStr.indexOf(' '));

    DEBUG_PRINT(F("COMANDO: Delete number:-->"));
    DEBUG_PRINT(commandStr);
    DEBUG_PRINT(F("<--\n"));
    Setup mySetup;
    boolean bRes = mySetup.deleteNumber(commandStr.c_str());
    if (bRes)
    {
      sendDeleteReplySms(commandStr.c_str());
      lcd.displayText("Borrado numero", commandStr);
      delay(5000);
      displayPhoneNumberList(mySetup);
    }
    //NOTA: Si me mandan borrar un número que no existe, la función de borrado devolverá false. Me debo asegurar
    //de borrar el mensaje de petición de borrado en cualquier caso, para que no quede atascando memoria
  }
  else if (commandStr.startsWith(SMS_COMMAND_QUERY_STATUS))
  {
    commandStr = commandStr.substring(strlen(SMS_COMMAND_QUERY_STATUS) + 1, commandStr.length());
    commandStr = commandStr.substring(0, commandStr.indexOf(' '));
    DEBUG_PRINT(F("COMANDO: Send Query to:-->"));
    DEBUG_PRINT(commandStr);
    DEBUG_PRINT(F("<--\n"));
    if (sendQueryReplySms(commandStr.c_str()))
    {
      lcd.displayText("Enviada temp a ", commandStr.c_str());
      delay(5000);
    }
  }
  
  //Borro el SMS porque o es un comando que ya se ha procesado, o no es un comando y nos ocupa memoria para nada.
  DEBUG_PRINT("Borrando SMS en posicion: " + String(smsIndex) + "\n");
  gprs.deleteSmsAtIndex(smsIndex);
}


boolean sendQueryReplySms (const char* phoneNumber)
{
  boolean bRes = false;
  String smsTxt = "ELSIS T. actual: " + String(currentTemp, FLOAT_DECIMAL_PLACES) +  "C. Alarma: " + String(alarmTemp, FLOAT_DECIMAL_PLACES)+ "C.";
  DEBUG_PRINT(smsTxt);
  DEBUG_PRINTLN();
  bRes = gprs.sendSms(phoneNumber, smsTxt);
  return bRes;
}

boolean sendAddReplySms (const char* phoneNumber)
{
  boolean bRes = false;
  String smsTxt = "ELSIS: Su telefono recibira a partir de ahora alarmas de temperatura.";
  DEBUG_PRINT(smsTxt);
  DEBUG_PRINTLN();
  bRes = gprs.sendSms(phoneNumber, smsTxt);
  return bRes;
}


boolean sendDeleteReplySms (const char* phoneNumber)
{
  boolean bRes = false;
  String smsTxt = "ELSIS: Su telefono ya no recibira mas alarmas de temperatura.";
  DEBUG_PRINT(smsTxt);
  DEBUG_PRINTLN();
  bRes = gprs.sendSms(phoneNumber, smsTxt);
  return bRes;
}

void displayPhoneNumberList(Setup mySetup)
{
  lcd.displayText ("Mostrando telef", "envio SMS alarma");
  DEBUG_PRINT(F("Mostrando telefonoos envio SMSs alarma\n"));
  delay(3000);

  char buffer[PHONE_NUMBER_BYTES + 1];
  for (int i = 0; i < mySetup.getPhoneNumberCount(); i++)
  {
    mySetup.getPhoneNumberAtIndex(i, buffer);
    DEBUG_PRINT("[" + String(i) + "]: " + buffer + "\n");
    lcd.displayText("Telefono " + String(i + 1), buffer);
    delay(3000);
  }
}

void displayCoverageIcon()
{
    int strength = gprs.getSignalStrength();
    if(strength == -1)
    {
      lcd.showCustomChar(COVERAGE_X, 1, 0);
    }  
    else if (strength >= 0 && strength < 33)
    {
      lcd.showCustomChar(COVERAGE_L, 1, 0);
    }
    else if (strength >= 33 && strength < 66)
    {
      lcd.showCustomChar(COVERAGE_M, 1, 0);
    }
    else if (strength >= 66 && strength < 99)
    {
      lcd.showCustomChar(COVERAGE_H, 1, 0);
    }
}
